package com.qinglei.recoup.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.qinglei.recoup.app.dao.RadarWechatAppMapper;
import com.qinglei.recoup.app.dao.RadarWechatAppSubscriptionMapper;
import com.qinglei.recoup.app.dao.WxDetailedMapper;
import com.qinglei.recoup.app.domain.RadarWechatApp;
import com.qinglei.recoup.app.domain.RadarWechatAppSubscription;
import com.qinglei.recoup.app.domain.WxDetailed;
import com.qinglei.recoup.app.pojo.RadarWechatAppSubscriptionEnum;
import com.qinglei.recoup.app.pojo.TagParam;
import com.qinglei.recoup.app.service.WxRadarService;
import com.qinglei.recoup.common.domain.CommonRes;
import com.qinglei.recoup.common.utils.RecoupUtil;
import com.qinglei.recoup.system.domain.*;
import com.qinglei.recoup.system.service.BedHealthDailyStatisticsService;
import com.qinglei.recoup.system.service.BedService;
import com.qinglei.recoup.system.service.RadarService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class WxRadarServiceImpl implements WxRadarService {
    @Autowired
    private WxDetailedMapper wxDetailedMapper;

    @Resource
    private RadarWechatAppMapper radarWechatAppMapper;

    @Autowired
    private BedService bedService;

    @Autowired
    private BedHealthDailyStatisticsService bedHealthDailyStatisticsService;

    @Autowired
    private RadarService radarService;

    @Value("${cuser.tenantId}")
    private Integer tenantId;
    @Autowired
    private RadarWechatAppSubscriptionMapper radarWechatAppSubscriptionMapper;

    @Override
    public CommonRes getDefaultRadarData(String startDate,String endDate) {
        String unionid = RecoupUtil.getCurrentUser().getUnionid();
        if(StringUtils.isEmpty(unionid)){
            return CommonRes.failed("获取用户信息有误！unionid为空");
        }
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("unionid",unionid);
        WxDetailed wxDetailed =  wxDetailedMapper.selectOne(queryWrapper);
        if(wxDetailed==null){
            return CommonRes.failed("尚未关注清雷微信公众平台");
        }
        Map<String,Object> resultMap = new HashMap<>();
        String openId = wxDetailed.getOpenid();
        QueryWrapper queryRadarCount = new QueryWrapper();
        queryRadarCount.eq("open_id",openId);
        queryRadarCount.eq("is_deleted",0);

        Integer radarCount = radarWechatAppMapper.selectCount(queryRadarCount);
        resultMap.put("radarCount",radarCount);
        RadarWechatApp radarWechatApp = radarWechatAppMapper.selectOne(Wrappers.<RadarWechatApp>lambdaQuery().eq(RadarWechatApp::getOpenId,openId).eq(RadarWechatApp::getIsDefault,1));
        if(radarWechatApp == null){
            return CommonRes.failed("未找到该微信号绑定的默认设备");
        }
        LocalDate localDate = LocalDate.now();
        Bed bed = bedService.getBedBySn(radarWechatApp.getSnCode());
        if(bed==null){
            return CommonRes.failed("未找到该设备绑定的床位");
        }

        List<Map<String,Object>> reportList = new ArrayList<>();
        LocalDate startDated =  LocalDate.parse(startDate);
        LocalDate endDateDated =  LocalDate.parse(endDate);
        int dayNum = Math.abs((int)(endDateDated.toEpochDay() - startDated.toEpochDay()));
        for(int i=dayNum;i>=0;i--){
            LocalDate currs = endDateDated.minusDays(i);
            DayOfWeek dayOfWeek =currs.getDayOfWeek();
            BedHealthShareParam bedHealthShareParam = new BedHealthShareParam();
            System.out.println(currs+"|"+getdayOfWeek(dayOfWeek));
            bedHealthShareParam.setBedId(bed.getId());
            bedHealthShareParam.setStartDate(currs.toString());
            bedHealthShareParam.setEndDate(currs.toString());
            BedHealthDailyStatistics bedHealthDailyStatistics =  bedHealthDailyStatisticsService.selectBedHealthDailyStatistics(bedHealthShareParam);
            Map<String,Object> data  = new HashMap<>();
            String[] dataArry = currs.toString().split("-");
            data.put("day",dataArry[1]+"-"+dataArry[2]);
            data.put("week",getdayOfWeek(dayOfWeek));
            data.put("date",currs.toString());
            if(bedHealthDailyStatistics!=null && bedHealthDailyStatistics.getResultFlag()==0){
                data.put("score",bedHealthDailyStatistics.getScore());
                data.put("haveHealthReport",1);
            }else {
                data.put("score",0);
                data.put("haveHealthReport",0);
            }
            reportList.add(data);
        }

        QueryWrapper queryDay = new QueryWrapper();
        queryDay.eq("sn_code",radarWechatApp.getSnCode());
        queryDay.eq("open_id",wxDetailed.getOpenid());
        queryDay.eq("is_deleted",0);
        queryDay.eq("type", RadarWechatAppSubscriptionEnum.DAILY.getCode());
        RadarWechatAppSubscription radarWechatAppSubscriptionDay = radarWechatAppSubscriptionMapper.selectOne(queryDay);
        if(radarWechatAppSubscriptionDay==null){
            resultMap.put("isSubscribeDayDaily",0);
        }else {
            resultMap.put("isSubscribeDayDaily",1);

        }

        QueryWrapper queryAlarm = new QueryWrapper();
        queryAlarm.eq("sn_code",radarWechatApp.getSnCode());
        queryAlarm.eq("open_id",wxDetailed.getOpenid());
        queryAlarm.eq("is_deleted",0);
        queryAlarm.eq("type", RadarWechatAppSubscriptionEnum.ALARM.getCode());
        RadarWechatAppSubscription radarWechatAppSubscriptionAlarm =  radarWechatAppSubscriptionMapper.selectOne(queryAlarm);
        if(radarWechatAppSubscriptionAlarm==null){
            resultMap.put("isSubscribeAlarm",0);
        }else {
            resultMap.put("isSubscribeAlarm",1);
        }

        resultMap.put("bed",bed);
        resultMap.put("snCode",radarWechatApp.getSnCode());
        resultMap.put("tag",radarWechatApp.getTag());
        resultMap.put("reportList",reportList);
        return CommonRes.ok(resultMap);
    }


    @Override
    public CommonRes setDefaultRadarData(TagParam tagParam) {
        String unionid = RecoupUtil.getCurrentUser().getUnionid();
        if(StringUtils.isEmpty(unionid)){
            return CommonRes.failed("获取用户信息有误！unionid为空");
        }
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("unionid",unionid);
        WxDetailed wxDetailed =  wxDetailedMapper.selectOne(queryWrapper);
        if(wxDetailed==null){
            return CommonRes.failed("尚未关注清雷微信公众平台");
        }

        String openId = wxDetailed.getOpenid();

        QueryWrapper queryWrapper1 = new QueryWrapper();
        queryWrapper1.eq("is_deleted",0);
        queryWrapper1.eq("sn_code",tagParam.getSnCode());
        queryWrapper1.eq("open_id",openId);
        queryWrapper1.eq("is_default",0);

        RadarWechatApp oldRadarWechatApp = radarWechatAppMapper.selectOne(queryWrapper1);

        if(oldRadarWechatApp==null){
            return CommonRes.failed("设备不存在,或者已经设为默认");
        }else{
            UpdateWrapper updateWrapper = new UpdateWrapper();
            updateWrapper.set("is_default",1);
            updateWrapper.eq("id",oldRadarWechatApp.getId());
            radarWechatAppMapper.update(null,updateWrapper);

            UpdateWrapper updateWrapper1 = new UpdateWrapper();
            updateWrapper1.set("is_default",0);
            updateWrapper1.eq("open_id",openId);
            updateWrapper1.ne("id",oldRadarWechatApp.getId());
            radarWechatAppMapper.update(null,updateWrapper1);
        }

        return CommonRes.ok("设置成功");
    }


    public static String  getdayOfWeek(DayOfWeek dayOfWeek){
        switch (dayOfWeek.toString()){
            case "MONDAY":
                return "周一";
            case "TUESDAY" :
                return "周二";
            case "WEDNESDAY" :
                return "周三";
            case "THURSDAY" :
                return "周四";
            case "FRIDAY" :
                return "周五";
            case "SATURDAY" :
                return "周六";
            case "SUNDAY" :
                return "周日";
            default: return "";
        }
    }


}
